/*
 * @Author: IBOSS 2776641037@qq.com
 * @Date: 2025-08-15 13:36:51
 * @LastEditors: IBOSS 2776641037@qq.com
 * @LastEditTime: 2025-08-19 16:44:07
 * @FilePath: \hm-admin\src\utils\reuqest.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { TOKEN_KEY } from '@/constants'

// 定义请求方法类型
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'

const service = axios.create({
  //baseURL: 'https://api-hmzs.itheima.net/api',
  baseURL: 'https://api.nuojie.cn/adminapi',
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    const getCookie = (name: string) => {
      const pair = document.cookie.split('; ').find(row => row.startsWith(name + '='))
      return pair ? decodeURIComponent(pair.split('=')[1]) : undefined
    }
    const token = getCookie(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY) || undefined
    if (token) {
      config.headers = config.headers || {}
      // 按后端要求使用自定义头键名 Authori-Zation
      ;(config.headers as Record<string, string>)["Authori-Zation"] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  },
)
// 后端返回值类型
export interface ServiceResponse<T> {
  code: number;
  msg: string;
  data: T;
}

// 添加request函数
// 请求工具函数
export const request = <T = unknown>(
  url: string,
  method: Method = "GET", // 默认请求方式 GET
  submitData?: object
) => {
  // 通过泛型约束返回值类型
  return service.request<T, ServiceResponse<T>>({
    url,
    method,
    // 根据请求方式，动态设置请求参数
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
  });
};

export default service
